package com.gdssoft.pdaweb.service.ws.security;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ws.security.WSPasswordCallback;
import org.apache.ws.security.WSSecurityException;

public class ServerPasswordCallback implements CallbackHandler {
	
	private Map<String, String> passwords = new HashMap<String, String>();
	
	private transient final Log logger = LogFactory.getLog(getClass());
	
    public ServerPasswordCallback() {
        passwords.put("pda", "123456");
        passwords.put("eam", "123456");
    }

	@Override
	public void handle(Callback[] callbacks) throws IOException,
			UnsupportedCallbackException {
		
		logger.debug("验证服务请求的凭证");
		
		for (int i = 0; i < callbacks.length; i++) {
            WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
            if (!passwords.containsKey(pc.getIdentifier()))
                throw new UnsupportedCallbackException(pc, "用户不匹配！");
            //客户端传来的密码是经过加密的，getPassword没办法得到，
            //密码的比较是自动完成的
            pc.setPassword(passwords.get(pc.getIdentifier()));
            /*
            String pass = passwords.get(pc.getIdentifier());
            String pwd = pc.getPassword();

            if (pwd == null || !pwd.equals(pass)) {
                throw new UnsupportedCallbackException(pc,"密码不匹配！");
            }
            */
        }
	}

}
